package postgresql

import (
	"database/sql"
	"fmt"
	"go_auto/project/init_project"
	"log"

	_ "github.com/lib/pq"
)

// 连接数据库
func GetDB() *sql.DB {
	postgreSqlinfo := init_project.ProjectConfig.Get("postgresql")
	// var postgreSqlinfo = initProject.ProjectConfig["postgresql"].(map[string]interface{})
	var psqlInfo string
	if postgreSqlinfo != nil {
		psqlInfo = fmt.Sprintf(
			"host=%s port=%.0f user=%s password=%s dbname=%s sslmode=disable",
			postgreSqlinfo.(map[string]interface{})["postgresql_host"],
			postgreSqlinfo.(map[string]interface{})["postgresql_port"],
			postgreSqlinfo.(map[string]interface{})["postgresql_user"],
			postgreSqlinfo.(map[string]interface{})["postgresql_password"],
			postgreSqlinfo.(map[string]interface{})["postgresql_dbname"],
		)
	}

	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		log.Fatal(err)
		return nil
	}
	err = db.Ping()
	if err != nil {
		log.Fatal(err)
		return nil
	}
	fmt.Println("successfull connected!")

	return db
}

// 查询方法
func QuerySql(db *sql.DB, sqlStatement string) []map[string]string {

	rows, err := db.Query(sqlStatement)
	if err != nil {
		panic(err)
	}
	defer rows.Close()
	//列出所有查询结果的字段名
	cols, _ := rows.Columns()

	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))

	//query.scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))

	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}
	res := make([]map[string]string, 0)
	for rows.Next() {
		_ = rows.Scan(scans...)
		row := make(map[string]string)
		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		res = append(res, row)
	}
	fmt.Printf("数据查询：%s:%s", sqlStatement, res)
	return res
}

// 插入更新单条语句
func ExecSql(db *sql.DB, sqlStatement string, sqlParameter_swap []string) {

	var sqlParameter []interface{}

	for _, value := range sqlParameter_swap {
		sqlParameter = append(sqlParameter, value)
	}

	stmt, err := db.Prepare(sqlStatement)
	if err != nil {
		panic(err)
	}

	res, err := stmt.Exec(sqlParameter...)
	if err != nil {
		panic(err)
	}

	fmt.Printf("res = %d", res)
}
